package com.example.myproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.myproject.mapper.PromotionMapper;
import com.example.myproject.model.Promotion;
import com.example.myproject.model.enums.PromotionType;
import com.example.myproject.service.PromotionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class PromotionServiceImpl implements PromotionService {

    private final PromotionMapper promotionMapper;

    @Override
    @Transactional
    public void createPromotion(Long torrentId,
                                PromotionType type,
                                LocalDateTime start,
                                LocalDateTime end,
                                String name) {

        Promotion p = new Promotion();
        p.setTorrentId(torrentId);
        p.setPromotionType(type);
        p.setPromotionName(name);
        p.setStartTime(start);
        p.setEndTime(end);
        p.setDownloadRate(type.getDownloadRate());
        p.setUploadRate(type.getUploadRate());

        promotionMapper.insert(p);
    }

    @Override
    public Optional<Promotion> getActivePromotion(Long torrentId) {
        LocalDateTime now = LocalDateTime.now();
        return Optional.ofNullable(
                promotionMapper.selectOne(
                        new LambdaQueryWrapper<Promotion>()
                                .eq(Promotion::getTorrentId, torrentId)
                                .le(Promotion::getStartTime, now)
                                .ge(Promotion::getEndTime,   now)
                                .last("LIMIT 1")));
    }
}
